<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Models\Route;
use Illuminate\Http\Request;
use App\Models\Acl;

class RouteController extends Controller
{
    public function __construct()
    {

    }

    public function listAction()
    {
        $pageSize = 20;
        $paginator = Route::orderBy('nav_id', 'asc')->orderBy('route_id')->paginate($pageSize);

        return view('setting/route/list', ['paginator' => $paginator]);
    }

    public function get(int $id)
    {
        $route = Route::find($id);
        $route->is_nav = boolval($route->is_nav);
        return response()->json($route);
    }

    public function editAction(Request $request, int $id)
    {
        $this->validate($request, [
            'label' => 'required',
            'nav_id' => 'required|int',
            'uri' => 'required',
            'method' => 'required',
            'action' => 'required',
            'is_nav' => 'required',
        ]);

        $route = new Route();
        if ($request->get('route_id')) {
            $route = Route::find($request->get('route_id'));
        }

        $uri = $request->get('uri');
        if (substr($uri, 0, 1) == "/") {
            $uri = substr($uri, 1, -1);
        }

        $route->uri    = $uri;
        $route->label  = $request->get('label');
        $route->nav_id = $request->get('nav_id');
        $route->method = $request->get('method');
        $route->action = $request->get('action');
        $route->is_nav = $request->get('is_nav');
        $route->save();

        return redirect('route');
    }

    public function delete($id)
    {
        Acl::where('route_id')->delete();
        $route = Route::find($id)->delete();
        return redirect('route');
    }
}
